import { useControllableValue } from "ahooks";
import {
  forwardRef,
  PropsWithChildren,
  useEffect,
  useImperativeHandle,
  useRef,
  useState,
} from "react";
import Vditor from "vditor";
import "vditor/dist/index.css";

interface IVditorEditorProps {
  className?: string;
  value?: string;
  onChange?: (s: string) => void;
}

export const VditorEditor = forwardRef(VditorEditorFn);
export function VditorEditorFn(
  props: PropsWithChildren<IVditorEditorProps>,
  ref: any
) {
  const [value, setValue] = useControllableValue(props);
  const containerRef = useRef(null);
  const vdRef = useRef(null);

  useImperativeHandle(ref, () => {
    return {
      getValue: () => {
        return vdRef.current?.getValue();
      },
    };
  });

  useEffect(() => {
    if (!value?.trim()) {
      return;
    }
    vdRef.current = new Vditor(containerRef.current, {
      cdn: "/vditor",
      value,
      toolbar: [
        "undo",
        "redo",
        "|",
        "headings",
        "bold",
        "italic",
        "|",
        "list",
        "ordered-list",
        "check",
        "link",
        "table",
      ],
      toolbarConfig: {
        hide: false,
      },
      cache: {
        enable: false,
      },
      mode: "wysiwyg",
      input: (value) => {
        setValue(value);
      },
    });
    // Clear the effect
    return () => {
      try {
        vdRef.current?.destroy();
      } catch (err) {
        // console.error(err);
      }
      vdRef.current = null;
    };
  }, [value]);

  return (
    <div ref={containerRef} className="my-vditor">
      {props.children}
    </div>
  );
}
